package com.feihua.starter.comm.component.task;

import com.feihua.starter.comm.Constants;
import com.feihua.starter.comm.CalendarUtil;
import com.feihua.starter.comm.component.MsgTemplate;
import com.feihua.starter.service.api.ApiHdbActivityPoService;
import com.feihua.starter.service.api.ApiHdbAttendPoService;
import com.feihua.starter.service.api.ApiHdbMsgPoService;
import com.feihua.starter.service.modules.hdb.dto.HdbAttendDto;
import com.feihua.starter.service.modules.hdb.po.HdbActivityPo;
import com.feihua.starter.service.modules.hdb.po.HdbAttendPo;
import com.feihua.starter.service.modules.hdb.po.HdbMsgPo;
import feihua.jdbc.api.pojo.BasePo;
import org.apache.commons.collections.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.PropertySource;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.List;

/**
 * @Auther: wzn
 * @Date: 2018/8/6 11:31
 * @Description:
 */
@Component
@PropertySource("classpath:config/application-cron.properties")
public class HDBTask {
    private static Logger logger = LoggerFactory.getLogger(HDBTask.class);

    @Autowired
    private ApiHdbActivityPoService apiHdbActivityPoService;

    @Autowired
    private ApiHdbAttendPoService apiHdbAttendPoService;

    @Autowired
    private ApiHdbMsgPoService apiHdbMsgPoService;

    /**
     * 更新活动
     *
     * @param count
     * @param hdbActivityPos
     * @param status
     *
     * @return
     */
    private Integer updateHdbActivity(Integer count, List<HdbActivityPo> hdbActivityPos, String status) {
        if (CollectionUtils.isNotEmpty(hdbActivityPos)) {
            for (HdbActivityPo hdbActivityPo : hdbActivityPos) {
                try {
                    HdbActivityPo po = new HdbActivityPo();
                    po.setId(hdbActivityPo.getId());
                    po.setStatus(status);
                    po.setUpdateAt(new Date());
                    apiHdbActivityPoService.updateByPrimaryKeySelective(po);
                    addMsg(hdbActivityPo, status);
                    count++;
                } catch (Exception e) {
                    logger.error(e.getMessage(), e);
                }
            }
        }
        return count;
    }

    /**
     * 给参与上发消息
     *
     * @param hdbActivityPo
     * @param status
     */
    private void addMsg(HdbActivityPo hdbActivityPo, String status) {
        HdbAttendPo queryPo = new HdbAttendPo();
        queryPo.setActivityId(hdbActivityPo.getId());
        queryPo.setDelFlag(BasePo.YesNo.N.name());
        queryPo.setStatus(BasePo.YesNo.Y.name());
        final List<HdbAttendDto> hdbAttendDtos = apiHdbAttendPoService.selectList(queryPo);
        if (CollectionUtils.isNotEmpty(hdbAttendDtos)) {
            for (HdbAttendDto hdbAttendDto : hdbAttendDtos) {
                HdbMsgPo msgPo = new HdbMsgPo();
                msgPo.setReadFlag(BasePo.YesNo.N.name());
                msgPo.setUserId(hdbAttendDto.getUserId());
                msgPo.setActivityId(hdbActivityPo.getId());
                msgPo.setSources(Constants.MsgSource.MSG_SYSTEM.getCode());
                msgPo.setTitle(Constants.MsgSource.MSG_SYSTEM.getName());
                msgPo.setContent(String.format(MsgTemplate.status_activity_msg, hdbActivityPo.getTitle(), Constants.ActivityStatus.getEnumBy(status).getName()));
                apiHdbMsgPoService.preInsert(msgPo, hdbAttendDto.getUserId());
                apiHdbMsgPoService.insert(msgPo);
            }
        }
    }

    /**
     * 个人活动
     */
    @Scheduled(cron = "${HDBTask.self.cron}")
    public void doSelf() {
        long start = System.currentTimeMillis();
        logger.info("==>个人活动进行中状态更新，开始");
        Integer count = 0;
        //个人状态：未开始-进行中-已结束 ：未开始-》进行中
        final List<HdbActivityPo> hdbActivityPos = apiHdbActivityPoService.selectTimingByNow(Constants.ActivityType.SELF.getCode(), Constants.ActivityStatus.NOT_START.getCode(), new Date(), 1);
        count = updateHdbActivity(count, hdbActivityPos, Constants.ActivityStatus.STARTING.getCode());

        //
        logger.info("<==个人活动进行中状态更新，结束，更新：{}，总耗时：{}", count, CalendarUtil.formatTime(System.currentTimeMillis() - start));
    }


    /**
     * 组队活动
     */
    @Scheduled(cron = "${HDBTask.team.cron}")
    public void doTeam() {
        long start = System.currentTimeMillis();
        logger.info("==>组队活动进行中状态更新，开始");
        Integer applyingCount = 0;
        Integer quotaFullCount = 0;
        //组队状态：未开始-报名中-名额满-进行中-已结束：报名中-》进行中
        final List<HdbActivityPo> applyings = apiHdbActivityPoService.selectTimingByNow(Constants.ActivityType.TEAM.getCode(), Constants.ActivityStatus.APPLYING.getCode(), new Date(), 1);
        applyingCount = updateHdbActivity(applyingCount, applyings, Constants.ActivityStatus.STARTING.getCode());

        //组队状态：未开始-报名中-名额满-进行中-已结束：名额满-》进行中
        final List<HdbActivityPo> quotaFulls = apiHdbActivityPoService.selectTimingByNow(Constants.ActivityType.TEAM.getCode(), Constants.ActivityStatus.QUOTA_FULL.getCode(), new Date(), 1);
        quotaFullCount = updateHdbActivity(quotaFullCount, quotaFulls, Constants.ActivityStatus.STARTING.getCode());

        //
        logger.info("<==组队活动进行中状态更新，结束，报名中状态更新：{}，名额满状态更新：{}，总耗时：{}", applyingCount, quotaFullCount, CalendarUtil.formatTime(System.currentTimeMillis() - start));
    }

    /**
     * 活动结束
     */
    @Scheduled(cron = "${HDBTask.activity.end.cron}")
    public void doActivityEnd() {
        long start = System.currentTimeMillis();
        logger.info("==>个人/组队活动已结束状态更新，开始");
        Integer selfCount = 0;
        Integer teamCount = 0;
        //组队状态：未开始-报名中-名额满-进行中-已结束
        final List<HdbActivityPo> selfs = apiHdbActivityPoService.selectTimingByNow(Constants.ActivityType.SELF.getCode(), Constants.ActivityStatus.STARTING.getCode(), new Date(), -1);
        selfCount = updateHdbActivity(selfCount, selfs, Constants.ActivityStatus.END.getCode());

        //
        final List<HdbActivityPo> teams = apiHdbActivityPoService.selectTimingByNow(Constants.ActivityType.TEAM.getCode(), Constants.ActivityStatus.STARTING.getCode(), new Date(), -1);
        teamCount = updateHdbActivity(teamCount, teams, Constants.ActivityStatus.END.getCode());

        //
        logger.info("<==个人/组队活动已结束状态更新，结束，个人已结束状态更新：{}，组队已结束状态更新：{}，总耗时：{}", selfCount, teamCount, CalendarUtil.formatTime(System.currentTimeMillis() - start));
    }
}
